//
//  AttractionsVController.m
//  Travel assistant
//
//  Created by lanou3g on 16/2/29.
//  Copyright © 2016年 旅游助手. All rights reserved.
//

#import "AttractionsVController.h"
#import "AttractionsCell.h"

@interface AttractionsVController ()<UITextFieldDelegate,UITableViewDelegate, UITableViewDataSource, BMKPoiSearchDelegate>
{
    BMKPoiSearch *_jjPoiSearch;
    NSInteger curPage;
    CLLocationCoordinate2D location;
}
@property (nonatomic, strong) AttractionsDetailModel *attractionsDetailModel;
@property (nonatomic, strong) UITextField *textfield;
@property (nonatomic, strong) AttractionsDetailModel *attractionDetailModel;
@property (nonatomic, strong) JJSearchBar *searchBar;

@end

@implementation AttractionsVController
static NSString *const attractionsCell = @"AttractionsCell";
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setNavigationBar];
    [self setDelegate];
    [self setRegisterCell];
    [self setBaiduMapSearchWithCity:@"北京" keyword:@"景点"];
}

- (void)setNavigationBar{
    self.searchBar = [JJSearchBar jjSearchBar];
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"搜索景点名称.....";
    //尺寸
    self.searchBar.frame = CGRectMake(0, 0, self.view.frame.size.width - 100, 30);
    //设置中间的标题内容
    self.navigationItem.titleView = self.searchBar;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self setBaiduMapSearchWithCity:@"北京" keyword:textField.text];
    [self.searchBar resignFirstResponder];
    return YES;
}
- (void)setBaiduMapSearchWithCity:(NSString *)city keyword:(NSString *)keyword{
    _jjPoiSearch = [[BMKPoiSearch alloc] init];
    _jjPoiSearch.delegate = self;
    
    curPage = 0;
    BMKCitySearchOption *citySearchOption = [[BMKCitySearchOption alloc] init];
    citySearchOption.pageIndex = (int)curPage;
    //分页数量，可选，默认为10，最多为50
    citySearchOption.pageCapacity = 50;
    citySearchOption.city = city;
    //搜索关键字
    citySearchOption.keyword = keyword;
    /**
     *城市POI检索
     *异步函数，返回结果在BMKPoiSearchDelegate的onGetPoiResult通知
     *@param option 城市内搜索的搜索参数类（BMKCitySearchOption）
     *@return 成功返回YES，否则返回NO
     */
    BOOL flag = [_jjPoiSearch poiSearchInCity:citySearchOption];
    if (flag) {
        NSLog(@"周边检索发送成功......");
    } else {
        NSLog(@"周边检索发送失败......");
    }
}
#pragma mark ---异步函数，返回结果在BMKPoiSearchDelegate的onGetPoiResult通知---

- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult*)result errorCode:(BMKSearchErrorCode)error
{
    self.attractionsArray = [NSArray arrayWithArray:result.poiInfoList];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.attractionsTableView reloadData];
    });
}



- (IBAction)addAttractions:(UIButton *)sender {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"添加景点" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        self.textfield = textField;
        self.textfield.placeholder = @"请输入景点名称";
        self.textfield.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.textfield.borderStyle = UITextBorderStyleRoundedRect;
    }];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.attractionsDetailModel = [AttractionsDetailModel object];
        [self.attractionsDetailModel setObject:self.textfield.text forKey:@"attractionName"];
        [self.attractionsDetailModel saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                NSLog(@"self.attractionsDetailModel存储成功.....");
            } else {
                NSLog(@"%@",error);
            }
        }];
        [self.navigationController popViewControllerAnimated:YES];
    }]];
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
}

- (void)setDelegate{
    self.attractionsTableView.delegate = self;
    self.attractionsTableView.dataSource = self;
}


- (void)setRegisterCell{
    [self.attractionsTableView registerNib:[UINib nibWithNibName:@"AttractionsCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:attractionsCell];
}


/**下面是与TableView有关的代理方法*/
- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.attractionsArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AttractionsCell *cell = [tableView dequeueReusableCellWithIdentifier:attractionsCell forIndexPath:indexPath];
    cell.attractionsModel = self.attractionsArray[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BMKPoiInfo *model = self.attractionsArray[indexPath.row];
    [self addAttractionWith:model];
    [self.navigationController popViewControllerAnimated:YES];
}
- (CGFloat )tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 55;
}







- (void)addAttractionWith:(BMKPoiInfo *)model{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"亲，你要去那吗？" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self.attractionsDetailModel = [AttractionsDetailModel object];
        [self.attractionsDetailModel setObject:model.name forKey:@"attractionName"];
        [self.attractionsDetailModel setObject:model.address forKey:@"attractionAddress"];
        [self.attractionsDetailModel saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                NSLog(@"self.attractionsDetailModel 存储成功......");
            } else {
                NSLog(@"%@",error);
            }
        }];
    }]];
    [self presentViewController:alertController animated:YES completion:^{
        
    }];

}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
